package com.example.springboottest.student.service.impl;

import com.example.springboottest.student.service.LeaveActivitiService;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.DeploymentBuilder;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service("activitiService")
public class LeaveActivitiServiceImpl implements LeaveActivitiService {
    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    HistoryService historyService;

    @Autowired
    ProcessEngine processEngine;

    private String relativePath = "processes/leave/";

    @Override
    public void doDeployWFTemplate(String wfName) {
        /**
         * 以bpmn或者bpmn20.xml结尾的资源内容才会去部署流程!!!!
         */
        // 创建一个部署对象
        Deployment deployment = repositoryService.createDeployment()
                .name(wfName).key("LeaveProcessV3")
                .addClasspathResource(relativePath + wfName + ".bpmn")
                .addClasspathResource(relativePath + wfName + ".png")
                .deploy();
        System.out.println("部署ID：" + deployment.getId());
        System.out.println("部署名称：" + deployment.getName());
    }

    @Override
    public Deployment doViewWFTemplate(String wfName) {
        DeploymentBuilder deploymentBuilder = repositoryService.createDeployment().name(wfName);
        Deployment deployment = null;
        try {
            deployment = deploymentBuilder.addClasspathResource(relativePath + wfName + ".bpmn")
                    .addClasspathResource(relativePath + wfName + ".png").deploy();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return deployment;
    }

    @Override
    public void doStartProcess(String processDefinitionKey, Integer days) {
        Map<String, Object> map = new HashMap<>();

        //使用UEL 表达式设置

        // 学生填写申请单    Assignee：${student}
        map.put("student", "轩轩");

        // 请假天数小于5天   班主任审批    Assignee：${teacher}
        map.put("teacher", "孔老师");

        // 请假天数大于等于5天  校长审批    Assignee：${master}
        map.put("master", "方校长");

        map.put("days", days);

        ProcessInstance instance = runtimeService.startProcessInstanceByKey(processDefinitionKey, map);
        System.out.println("流程实例ID:" + instance.getId());
        System.out.println("流程定义ID:" + instance.getProcessDefinitionId());
    }

    @Override
    public List<Map<String, String>> doSearchProcess(String processDefinitionKey) {
        List<Map<String, String>> maps = new ArrayList<>();
        List<ProcessInstance> list = runtimeService.createProcessInstanceQuery().processDefinitionKey(processDefinitionKey).list();
        if (CollectionUtils.isNotEmpty(list)) {
            Map<String, String> map = null;
            for (ProcessInstance instance : list) {
                map = new HashMap<>();
                map.put("流程实例ID:", instance.getId());
                map.put("流程定义ID:", instance.getProcessDefinitionId());
                maps.add(map);
            }
        }
        return maps;
    }

    @Override
    public List<Map<String, String>> doSearchHistoryProcess(String processDefinitionKey) {
        List<Map<String, String>> maps = new ArrayList<>();
        /**
         * 由于activiti7默认mysql数据库，oracle数据库导致几个ACT_HI_*的表没有生成，目前查询不到数据
         */
        List<HistoricProcessInstance> list = historyService.createHistoricProcessInstanceQuery().processDefinitionKey(processDefinitionKey).finished().list();
        if (CollectionUtils.isNotEmpty(list)) {
            Map<String, String> map = null;
            for (HistoricProcessInstance instance : list) {
                map = new HashMap<>();
                map.put("流程实例ID:", instance.getId());
                map.put("流程定义ID:", instance.getProcessDefinitionId());
                maps.add(map);
            }
        }
        return maps;
    }

    @Override
    public List<String> doSearchTask(String processDefinitionKey, String userName) {
        //流程启动后，各各任务的负责人就可以查询自己当前需要处理的任务，查询出来的任务都是该用户的待办任务。
        List<Task> list = taskService.createTaskQuery()
                //流程实例key
                .processDefinitionKey(processDefinitionKey)
                //查询谁的任务
                .taskAssignee(userName == null ? "" : userName)
                .list();
        List<String> idList = new ArrayList<String>();

        if (CollectionUtils.isNotEmpty(list))
            for (Task task : list) {
                idList.add(task.getId());
                System.out.println("任务ID:" + task.getId());
                System.out.println("任务名称:" + task.getName());
                System.out.println("任务的创建时间:" + task.getCreateTime());
                System.out.println("任务的办理人:" + task.getAssignee());
                System.out.println("流程实例ID：" + task.getProcessInstanceId());
                System.out.println("执行对象ID:" + task.getExecutionId());
                System.out.println("流程定义ID:" + task.getProcessDefinitionId());
            }

        return idList;
    }

    @Override
    public void doDisposeTask(String taskId) {
        // 任务id
//        List<Task> tasks =  taskService.createTaskQuery().taskId(taskId).list();
        Map<String, Object> assMap = new HashMap<>();
        assMap.put("days", 6);
        taskService.complete(taskId, assMap);
        System.out.println("处理任务id：" + taskId);
    }
}